package com.wujunshen.redis.support;

import java.util.Arrays;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySource;

/**
 * @author frank woo(吴峻申) <br>
 * email:<a href="mailto:frank_wjs@hotmail.com">frank_wjs@hotmail.com</a> <br>
 * @date 2020/2/7 5:33 下午 <br>
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class PropertySourcesSupport {
    /**
     * 检查配置文件中是否包含某个前缀
     *
     * @param env    应用环境
     * @param prefix 要判断的前缀值
     * @return true为包含，false为不包含
     */
    public static boolean containsPropertyNamePrefix(Environment env, String prefix) {
        return env instanceof ConfigurableEnvironment
                && ((ConfigurableEnvironment) env)
                .getPropertySources().stream()
                .anyMatch(propertySource -> containsNamePrefix(propertySource, prefix));
    }
    
    /**
     * @param propertySource 配置类
     * @param prefix         要判断的前缀值
     * @return true为包含，false为不包含
     */
    private static boolean containsNamePrefix(PropertySource<?> propertySource, String prefix) {
        return propertySource instanceof EnumerablePropertySource
                && Arrays.stream(((EnumerablePropertySource<?>) propertySource).getPropertyNames())
                .anyMatch(propertyName -> propertyName.startsWith(prefix));
    }
}
